package com.ruoyi.system.policy;


import com.ruoyi.system.domain.PolicyDocuments;
import com.ruoyi.system.service.IPolicyDocumentsService;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.Selectable;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Component
public class MySpider implements PageProcessor {

    private final IPolicyDocumentsService service;

    public MySpider(IPolicyDocumentsService service) {
        this.service = service;
    }

    private Site site = Site.me().setRetryTimes(3).setSleepTime(1000);

    public void process(Page page) {
        List<PolicyDocuments> documentList = new ArrayList<>();
        Html html = page.getHtml();
        List<Selectable> liList = html.xpath("//div[@class='NewsList']/ul/li").nodes();
        for (Selectable li : liList) {
            String date = li.xpath("span/text()").get().trim();
            String title = li.xpath("a/text()").get();
            String href = li.xpath("a/@href").get();
            PolicyDocuments document = new PolicyDocuments(
                    title,
                    href,
                    LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                    "省教育局"
            );
            documentList.add(document);
        }
        service.saveBatch(documentList);
    }


    public Site getSite() {
        return site;
    }

    public void queryPolicy() {
        Spider spider = new Spider(new MySpider(service));
        spider.addUrl("https://jyt.guizhou.gov.cn/xwzx/tzgg/").run();
    }
}
